﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BestBuy.DAL;

namespace BestBuy.PageUser
{
    public partial class EditSellOffer : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["IDDN"].ToString().Equals(""))
            {
                Response.Redirect("~/Account/Login.aspx");
            }
            if (!IsPostBack)
            {
                loadDonVi();
                loadSellOffer(int.Parse(Request.Params["IdSellOffer"].ToString()));
            }
        }
        private static BangTinBan sell;
        const int MaxQuantity = 3;
        private void loadDonVi()
        {
            DDdonvi1.DataSource = cDonVi.getDonVi();
            DDdonvi1.DataTextField = "TenDonVi";
            DDdonvi1.DataValueField = "IDDonVi";
            DDdonvi1.DataBind();

            DDDonvi2.DataSource = cDonVi.getDonVi();
            DDDonvi2.DataTextField = "TenDonVi";
            DDDonvi2.DataValueField = "IDDonVi";
            DDDonvi2.DataBind();
        }
        private void loadSellOffer(int idselloffer)
        {
            sell = cManageSellOffer.loadInfo(idselloffer);
            tbSubject.Text = sell.TieuDe;
            tbKeyWord.Text = sell.TuKhoa;
            tbDescription.Text = sell.MoTa;
            List<DanhMucBan> dm = cManageSellOffer.loadcategory(idselloffer);
            foreach (var item in dm)
            {
                ListItem it = new ListItem();
                it.Value = item.IDDanhMuc.ToString();
                it.Text = cManageSellOffer.getNamCategory(item.IDDanhMuc);
                CategoryListBox.Items.Add(it);
            }
            DateTime startDate = DateTime.Parse(sell.NgayDang);
            DateTime endDate = DateTime.Parse(sell.ThoiHanDang);
            int days = (endDate - startDate).Days;
            try
            {
                DropDownList1.SelectedValue = days.ToString();
            }
            catch
            {
                DropDownList1.SelectedIndex = 0;
            }
            if (sell.HinhAnh != "")
            {
                ImagePhoto.Visible = true;
                ImagePhoto.ImageUrl = "~/Images/Product/" + sell.HinhAnh;
            }
            tbDeliverTime.Text = sell.KyHanGiaoHang;
            String[] str = sell.KhaNangCungCap.Split('/');
            tbSupply.Text = str[0];
            DDdonvi1.SelectedItem.Text = str[1];
            DDdate.SelectedItem.Text = str[2];
            tbPlace.Text = sell.NoiXuatXu;
            String[] str1 = sell.SoLuongDatToiThieu.Split('/');
            tbMiniOrder.Text = str1[0];
            DDDonvi2.SelectedItem.Text = str1[1];
            String[] str2 = sell.PhuongThucThanhToan.Split('+');
            for (int i = 0; i < CheckBoxList1.Items.Count; i++)
            {
                if (str2[i] == "1")
                {
                    CheckBoxList1.Items[i].Selected = true;
                }
            }

        }
        protected void lbtnChangeCategory_Click(object sender, EventArgs e)
        {
            LoadCategoriesIntoListBox(gvLevel1, null);
            lbLimitQuantity.Text = MaxQuantity - CategoryListBox.Items.Count + "";
            this.mpeDanhMuc.Show();
        }
        protected void gvLevel1_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            LinkButton hidIDDanhMuc = (LinkButton)e.Row.FindControl("LinkDanhMuc");
            if (hidIDDanhMuc != null)
            {
                int id = Int32.Parse(hidIDDanhMuc.Attributes["ObjectId"]);
                if (!CCongTy.HasChildren(id))
                {
                    CheckBox checkbox = (CheckBox)e.Row.FindControl("cbLevel");
                    Label lb = (Label)e.Row.FindControl("lbLevel");
                    if (checkbox != null && lb != null)
                    {
                        checkbox.Visible = true;
                        lb.Visible = false;
                    }
                }
            }
        }

        protected void gvLevel2_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            LinkButton hidIDDanhMuc = (LinkButton)e.Row.FindControl("LinkDanhMuc");
            if (hidIDDanhMuc != null)
            {
                int id = Int32.Parse(hidIDDanhMuc.Attributes["ObjectId"]);
                if (!CCongTy.HasChildren(id))
                {
                    CheckBox checkbox = (CheckBox)e.Row.FindControl("cbLevel");
                    Label lb = (Label)e.Row.FindControl("lbLevel");
                    if (checkbox != null && lb != null)
                    {
                        checkbox.Visible = true;
                        lb.Visible = false;
                    }
                }
            }
        }

        protected void gvLevel3_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            LinkButton hidIDDanhMuc = (LinkButton)e.Row.FindControl("LinkDanhMuc");
            if (hidIDDanhMuc != null)
            {
                int id = Int32.Parse(hidIDDanhMuc.Attributes["ObjectId"]);
                if (!CCongTy.HasChildren(id))
                {
                    CheckBox checkbox = (CheckBox)e.Row.FindControl("cbLevel");
                    Label lb = (Label)e.Row.FindControl("lbLevel");
                    if (checkbox != null && lb != null)
                    {
                        checkbox.Visible = true;
                        lb.Visible = false;
                    }
                }
            }
        }
        protected void cbLevel_CheckedChanged(object sender, EventArgs e)
        {
            this.mpeDanhMuc.Show();
        }
        protected void LinkDanhMucLevel1_Click(object sender, EventArgs e)
        {
            LinkButton senderButton = sender as LinkButton;
            int id = 0;
            if (Int32.TryParse(senderButton.Attributes["ObjectId"], out id))
            {
                gvLevel3.DataSource = null;
                gvLevel3.DataBind();
                LoadCategoriesIntoListBox(gvLevel2, id);
            }
            this.mpeDanhMuc.Show();
        }

        protected void LinkDanhMucLevel2_Click(object sender, EventArgs e)
        {
            LinkButton senderButton = sender as LinkButton;
            int id = 0;
            if (Int32.TryParse(senderButton.Attributes["ObjectId"], out id))
            {
                LoadCategoriesIntoListBox(gvLevel3, id);
            }
            this.mpeDanhMuc.Show();
        }

        protected void LinkDanhMucLevel3_Click(object sender, EventArgs e)
        {
            this.mpeDanhMuc.Show();
        }
        private bool LoadCategoriesIntoListBox(GridView control, int? parentCatID)
        {
            var cats = CCongTy.GetChildrenOfCategory(parentCatID);
            control.DataSource = cats;
            control.DataBind();
            return cats != null && cats.Count > 0;
        }
        private bool ExistCategoryInList(int IDCategory)
        {
            foreach (ListItem item in CategoryListBox.Items)
            {
                if (int.Parse(item.Value) == IDCategory)
                    return true;
            }
            return false;
        }

        private void AddCategoryToList(int IDCategory)
        {
            if (!ExistCategoryInList(IDCategory))
            {
                DanhMuc dm = CCongTy.GetCategoryByID(IDCategory);
                ListItem item = new ListItem();
                item.Value = dm.IDDanhMuc.ToString();
                item.Text = dm.TenDanhMuc;
                CategoryListBox.Items.Add(item);
            }
        }
        protected void btnAddCategory_OnClick(object sender, EventArgs e)
        {
            try
            {
                int id = 0;
                for (int i = 0; i < gvLevel1.Rows.Count; i++)
                {
                    if (CategoryListBox.Items.Count == MaxQuantity)
                    {
                        return;
                    }
                    CheckBox chk = (CheckBox)gvLevel1.Rows[i].FindControl("cbLevel");
                    if (chk != null)
                    {
                        if (chk.Checked == true && chk.Enabled == true)
                        {
                            id = int.Parse(chk.Attributes["ObjectId"]);
                            AddCategoryToList(id);
                        }
                    }
                }
                for (int i = 0; i < gvLevel2.Rows.Count; i++)
                {
                    if (CategoryListBox.Items.Count == MaxQuantity)
                    {
                        return;
                    }
                    CheckBox chk = (CheckBox)gvLevel2.Rows[i].FindControl("cbLevel");
                    if (chk != null)
                    {
                        if (chk.Checked == true && chk.Enabled == true)
                        {
                            id = int.Parse(chk.Attributes["ObjectId"]);
                            AddCategoryToList(id);
                        }
                    }
                }
                for (int i = 0; i < gvLevel3.Rows.Count; i++)
                {
                    if (CategoryListBox.Items.Count == MaxQuantity)
                    {
                        return;
                    }
                    CheckBox chk = (CheckBox)gvLevel3.Rows[i].FindControl("cbLevel");
                    if (chk != null)
                    {
                        if (chk.Checked == true && chk.Enabled == true)
                        {
                            id = int.Parse(chk.Attributes["ObjectId"]);
                            AddCategoryToList(id);
                        }
                    }
                }
                lbThongBaoAddCategory.Text = "Add categories success.";
                lbThongBaoAddCategory.CssClass = "success";
                lbThongBaoAddCategory.Visible = true;
            }
            catch
            {
                lbThongBaoAddCategory.Text = "Add categories error.";
                lbThongBaoAddCategory.CssClass = "error";
                lbThongBaoAddCategory.Visible = true;
            }
            lbLimitQuantity.Text = MaxQuantity - CategoryListBox.Items.Count + "";
            this.mpeDanhMuc.Show();
        }
        protected void btnCancel_OnClick(object sender, EventArgs e)
        {
            lbThongBaoAddCategory.Visible = false;
            lbThongBaoAddCategory.Text = "";
        }
        protected void btRemoveSelect_Click(object sender, EventArgs e)
        {
            if (CategoryListBox.SelectedItem != null)
            {
                int index = CategoryListBox.SelectedIndex;
                CategoryListBox.Items.RemoveAt(index);
            }
        }

        protected void btUpdate_Click(object sender, EventArgs e)
        {
            sell.TieuDe = tbSubject.Text;
            sell.TuKhoa = tbKeyWord.Text;
            sell.MoTa = tbDescription.Text;
            int thoihandang = int.Parse(DropDownList1.SelectedItem.Value);
            DateTime startDate = DateTime.Parse(sell.NgayDang);
            sell.ThoiHanDang = startDate.AddDays(thoihandang).ToShortDateString();
            if (UploadPhoto.HasFile)
            {
                sell.HinhAnh = UploadPhoto.FileName;
                String url = Server.MapPath("~/Images/Product/") + UploadPhoto.FileName;
                UploadPhoto.SaveAs(url);
            }
            sell.KyHanGiaoHang = tbDeliverTime.Text;
            sell.KhaNangCungCap = tbSupply.Text + "/" + DDdonvi1.SelectedItem.Text + "/" + DDdate.SelectedItem.Text;
            sell.NoiXuatXu = tbPlace.Text;
            sell.SoLuongDatToiThieu = tbMiniOrder.Text + "/" + DDDonvi2.SelectedItem.Text;
            int[] arr = { 0, 0, 0, 0 };
            for (int i = 0; i < CheckBoxList1.Items.Count; i++)
            {
                if (CheckBoxList1.Items[i].Selected)
                {
                    arr[i] = 1;
                }
            }
            sell.PhuongThucThanhToan = "";
            for (int i = 0; i < arr.Count(); i++)
            {
                sell.PhuongThucThanhToan = sell.PhuongThucThanhToan + arr[i].ToString() + "+";
            }
            cManageSellOffer.UpdateSellOffer(sell);
            cManageSellOffer.clearCategory(sell.IDBangTinBan);
            for (int i = 0; i < CategoryListBox.Items.Count; i++)
            {
                cManageSellOffer.UpdateCategorySellOffer(int.Parse(Request.Params["IdSellOffer"].ToString()),int.Parse(CategoryListBox.Items[i].Value));
            }
            Response.Redirect("ManageSellOffer.aspx");
        }

    }
}